package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.minio.MinIoTemplate;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.OcrUtil;
import com.heima.utils.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.AutoScanService;
import com.sun.org.apache.xpath.internal.operations.Bool;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.tess4j.TesseractException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;


import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AutoScanServiceImpl implements AutoScanService {

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private WmUserMapper wmUserMapper;

    @Autowired
    private WmChannelMapper wmChannelMapper;

    @Autowired
    private GreenTextScan greenTextScan;

    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private MinIoTemplate minIoTemplate;

    @Autowired
    private IArticleClient articleClient;

    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;

    /**
     * 自动审核
     * @param newsId
     */
    @Override
    @Async
    public void autoScanWmNews(Integer newsId) throws Exception {
        if (newsId == null){
            log.error("文章审核入参id为空");
            return;
        }
        //根据传过来的新闻id,查询信息
        WmNews wmNews = wmNewsMapper.selectById(newsId);
        if (wmNews == null){
            log.error("入参id"+newsId+",查询新闻不存在");
            return;
        }
        //查出标题、封面图、以及所有内容
        String images = wmNews.getImages();
        String content = wmNews.getContent();
        String title = wmNews.getTitle();
        //从标题和内容中，抽取文字内容，进行审核
        String text = getText(title,content);
        //从封面图和内容中提取图片信息
        List<byte[]> imagesByteList = getImages(images,content);
       if (imagesByteList.size() != 0){
           //从图片中提取文字
           String textFromOcr = ocrCheck(imagesByteList);
           //将文字信息和图片中提取的文字信息拼接在一起
           text = text + "_" + textFromOcr;
       }
        //这里是DFA自定义敏感词检查
        Boolean dfaResult = dfaCheck(text);
        if (!dfaResult) {
            // DFA检测不通过的话，需要更新一下文章状态
            updateNewsStatus(newsId.intValue(),2, "DFA审核没通过", null);
            return;
        }

        Map textResult = greenTextScan.greeTextScan(text);
        Boolean textIsRight =  getSuggestion(textResult,newsId);
        if (!textIsRight){
            log.error("文字审核失败");
            return;
        }
        if (imagesByteList.size() > 0){
            //从封面图和内容中，抽取图片内容，进行审核
            Map imagesResult = greenImageScan.imageScan(imagesByteList);
            Boolean imagesIsRight =  getSuggestion(imagesResult,newsId);
            if (!imagesIsRight){
                log.error("图片审核失败");
                return;
            }
        }
        //插入文章，供app端查看
        ArticleDto dto = wmNews2ArticleDto(wmNews);
        ResponseResult responseResult = articleClient.saveArticle(dto);
        if (responseResult.getCode() != 200){
            log.error("文章保存失败");
            return;
        }
        //根据阿里云返回的结果进行更改新闻 wmNews信息
        Long articleId = (Long) responseResult.getData();
        updateNewsStatus(newsId, 9, "审核通过", articleId);

    }


    /**
     * 接收图片，提取图片里面的文字，并返回
     *
     * @param images 待检测的图片
     * @return 从图片中提取的文字
     */
    private String ocrCheck(List<byte[]> images) throws IOException, TesseractException {
        if (CollectionUtils.isEmpty(images)) {
            return "";
        }

        StringBuilder builder = new StringBuilder();
        for (byte[] image : images) {
            // 调用ocr工具类，提取里面的文字内容
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(image);
            BufferedImage read = ImageIO.read(byteArrayInputStream);

            String text = OcrUtil.doOcr(read);

            // 将文字内容组合成一个字符串，最终返回
            builder.append("_").append(text);
        }

        return builder.toString();
    }
    /**
     * DFA算法检测敏感词
     *
     * @param text 待检测的文字
     * @return 是否通过检测（true为通过，false为不通过）
     */
    private Boolean dfaCheck(String text) {
        if (StringUtils.isBlank(text)) {
            return true;
        }

        // 0.1 调用敏感词Mapper，查询所有敏感词
        QueryWrapper<WmSensitive> wrapper = new QueryWrapper<>();
        wrapper.select("sensitives");
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(wmSensitives)) {
            return true;
        }

        List<String> words = wmSensitives.stream().filter(Objects::nonNull).map(WmSensitive::getSensitives).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(words)) {
            return true;
        }

        // 0.2 DFA初始化
        SensitiveWordUtil.initMap(words);

        // 0.3 DFA敏感词匹配
        Map<String, Integer> result = SensitiveWordUtil.matchWords(text);

        // 0.4 判断结果
        return CollectionUtils.isEmpty(result);
    }


    /**
     * wmNews to ArticleDto
     * @param wmNews
     * @return
     */
    @Override
    public ArticleDto wmNews2ArticleDto(WmNews wmNews) {
        if (wmNews == null) {
            return null;
        }

        ArticleDto dto = new ArticleDto();
        BeanUtils.copyProperties(wmNews, dto);

        // 处理差异字段
        Integer userId = wmNews.getUserId();
        dto.setAuthorId(userId.longValue());
        WmUser wmUser = wmUserMapper.selectById(userId);
        if (wmUser != null) {
            dto.setAuthorName(wmUser.getName());
        }

        // 获取频道信息
        Integer channelId = wmNews.getChannelId();
        WmChannel wmChannel = wmChannelMapper.selectById(channelId);
        if (wmChannel != null) {
            dto.setChannelName(wmChannel.getName());
        }

        // 布局方式
        dto.setLayout(wmNews.getType());
        dto.setCreatedTime(new Date());

        return dto;
    }

    /**
     * 更新wmNews状态
     * @param newsId
     * @param status
     * @param reason
     * @param articleId
     */
    private Boolean updateNewsStatus(Integer newsId, Integer status, String reason, Long articleId) {
        WmNews wmNews = new WmNews();
        wmNews.setId(newsId);
        wmNews.setStatus(status.shortValue());
        wmNews.setReason(reason);
        wmNews.setArticleId(articleId);
        return wmNewsMapper.updateById(wmNews) < 1 ? false : true;
    }

    /**
     * {
     * 	"suggestion": "pass"
     * }
     * 解析阿里云审核结果，返回boolea
     * @param textResult
     * @return
     */
    private Boolean getSuggestion(Map textResult,Integer newsId) {
        if (CollectionUtils.isEmpty(textResult)){
            log.error("审核结果为空");
            return false;
        }

        String suggestion = (String) textResult.get("suggestion");
        if ("block".equals(suggestion)){
            //失败
            //更新状态为2 审核失败
            updateNewsStatus(newsId,2,"未通过",null);
            return false;
        }else if("review".equals(suggestion)){
            //不确定
            //更新状态为3 人工审核
            updateNewsStatus(newsId,3,"不确定",null);
            return false;
        }else if ("pass".equals(suggestion)){
            //成功
            return true;
        }
        return false;
    }

    /**
     * 封面图和内容转List<byte[]>供阿里云审核
     * @param images
     * @param content
     * @return
     */
    private List<byte[]>  getImages(String images, String content) {

        List<String> resultImages = new ArrayList<>();
        if (StringUtils.isNotEmpty(images)){
            String[] imagesList = images.split(",");
            List<String> StringasList = Arrays.asList(imagesList);
            resultImages.addAll(StringasList);
        }

        List<Map> contentList = JSON.parseArray(content, Map.class);
        List<String> resultContent = new ArrayList<>();
        if (!CollectionUtils.isEmpty(contentList)){
            for (Map item : contentList) {
                if (CollectionUtils.isEmpty(item)){
                    continue;
                }
                if ("images".equals(item.get("type"))){
                    resultContent.add((String) item.get("value"));
                }
            }

        }

        List<String> allImages = new ArrayList<>();
        allImages.addAll(resultImages);
        allImages.addAll(resultContent);

        List<byte[]> backResult = new ArrayList<>();
        for (String url : allImages) {
            if (StringUtils.isEmpty(url)){
                continue;
            }
            byte[] bytes = minIoTemplate.downLoadFile(url);
            backResult.add(bytes);
        }
        return backResult;
    }

    /**
     * 标题和内容，转换成String,供阿里云审核
     * @param title
     * @param content
     * @return
     */
    private String getText(String title, String content) {
        //从content中抽取文字内容
        List<Map> contentList = JSON.parseArray(content, Map.class);
        if (CollectionUtils.isEmpty(contentList)){
            log.error("文章内容为空");
            return title;
        }
        StringBuilder resultString = new StringBuilder();
        for (Map item : contentList) {
            if (CollectionUtils.isEmpty(item)){
                continue;
            }
            if ("text".equals(item.get("type"))){
                resultString.append((String) item.get("value"));
            }
        }
        resultString.append(title);
        return resultString.toString();
    }
}
